package com.hulman.oms.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.hulman.oms.bean.*;
import com.hulman.oms.dao.MaintainPlanDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: maxwellens
 */
@Service
public class MaintainPlanService
{
    @Autowired
    private MaintainPlanDao maintainPlanDao;
    @Autowired
    private MaintainPlanItemService maintainPlanItemService;

    public List<MaintainPlan> findMaintainPlans(Map<String, Object> map)
    {
        List<MaintainPlan> maintainPlans = maintainPlanDao.findMaintainPlans(map);
        for (MaintainPlan maintainPlan : maintainPlans)
        {
            maintainPlan.setPeriodText(maintainPlan.getPeriodName());
            maintainPlan.setUnitText(maintainPlan.getUnitName());
        }
        return maintainPlans;
    }

    public List<MaintainPlan> findLatestMaintainPlans()
    {
        return maintainPlanDao.findLatestMaintainPlans();
    }

    public List<MaintainPlan> findTodayMaintainPlans()
    {
        return maintainPlanDao.findTodayMaintainPlans();
    }

    public Integer findMaintainPlansCount(Map<String, Object> map)
    {
        return maintainPlanDao.findMaintainPlansCount(map);
    }

    public Result findMaintainPlansResult(Map<String, Object> map)
    {
        Integer page = (Integer) map.get("page");
        Integer limit = (Integer) map.get("limit");
        if (page != null && limit != null)
        {
            map.put("start", (page - 1) * limit);
            map.put("length", limit);
        }
        int count = maintainPlanDao.findMaintainPlansCount(map);
        List<MaintainPlan> data = findMaintainPlans(map);
        return new Result(data, count);
    }

    public MaintainPlan findMaintainPlanById(Integer id)
    {
        return maintainPlanDao.findMaintainPlanById(id);
    }

    public void saveMaintainPlan(MaintainPlan maintainPlan)
    {
        if (maintainPlan.getId() != null && maintainPlan.getId() != 0)
        {
            maintainPlanDao.updateMaintainPlan(maintainPlan);
        } else
        {
            maintainPlanDao.insertMaintainPlan(maintainPlan);
        }
    }

    public void deleteMaintainPlanById(Integer id)
    {
        maintainPlanDao.deleteMaintainPlanById(id);
    }

    public Map<String, List> findMaintainPlanDetail(Integer id)
    {
        Map<String, List> map = new LinkedHashMap<>();
        List<MaintainPlanItem> items = maintainPlanItemService.findMaintainPlanItemsByMaintainPlanId(id);
        for (MaintainPlanItem item : items)
        {
            if (! map.containsKey(item.getItem()))
            {
                List<String> entries = new ArrayList<>();
                map.put(item.getItem(), entries);
            }
            map.get(item.getItem()).add(item.getEntry());
        }
        return map;
    }

    public void changeMaintainPlanState(Integer id, Integer state)
    {
        maintainPlanDao.changeMaintainPlanState(id, state);
    }

    public List<MaintainContentItem> generateMaintainContent(Integer maintainPlanId)
    {
        List<MaintainPlanItem> items = maintainPlanItemService.findMaintainPlanItemsByMaintainPlanId(maintainPlanId);
        Map<String, List<MaintainPlanItem>> map = new LinkedHashMap<>();
        for (MaintainPlanItem item : items)
        {
            if (! map.containsKey(item.getItem()))
            {
                map.put(item.getItem(), new ArrayList<>());
            }
            List<MaintainPlanItem> maintainPlanItems = map.get(item.getItem());
            maintainPlanItems.add(item);
        }
        List<MaintainContentItem> result = new ArrayList<>();
        Integer id = 1;
        for (Map.Entry<String, List<MaintainPlanItem>> entry : map.entrySet())
        {
            MaintainContentItem maintainContentItem = new MaintainContentItem();
            maintainContentItem.setName(entry.getKey());
            List<MaintainContentEntry> entries = maintainContentItem.getEntries();
            for (MaintainPlanItem maintainPlanItem : entry.getValue())
            {
                entries.add(new MaintainContentEntry(id++, maintainPlanItem.getEntry(), false));
            }
            result.add(maintainContentItem);
        }
        return result;
    }

    /**
     * 导入excel文件
     *
     * @param excelFile
     */
    @Transactional(rollbackFor = Exception.class)
    public void importMaintainPlan(File excelFile)
    {
        //专项保养目录
        List<MaintainPlan> maintainPlans = EasyExcel.read(excelFile).head(MaintainPlan.class).sheet(0).doReadSync();
        for (int i = 0; i < maintainPlans.size(); i++)
        {
            MaintainPlan maintainPlan = maintainPlans.get(i);
            maintainPlan.setPeriod(MaintainPlan.parsePeriod(maintainPlan.getPeriodText()));
            maintainPlan.setUnit(MaintainPlan.parseUnit(maintainPlan.getUnitText()));
            maintainPlan.setState(0);
            saveMaintainPlan(maintainPlan);
            //专项保养项目
            List<MaintainPlanItem> maintainPlanItems = EasyExcel.read(excelFile).head(MaintainPlanItem.class)
                    .sheet(i + 1).doReadSync();
            for (MaintainPlanItem maintainPlanItem : maintainPlanItems)
            {
                maintainPlanItem.setMaintainPlanId(maintainPlan.getId());
                maintainPlanItemService.saveMaintainPlanItem(maintainPlanItem);
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void exportMaintainPlan(ExcelWriter excelWriter)
    {
        List<MaintainPlan> maintainPlans = findMaintainPlans(new HashMap<>());
        WriteSheet sheet0 = EasyExcel.writerSheet(0, "目录").head(MaintainPlan.class).build();
        excelWriter.write(maintainPlans, sheet0);
        for (int i = 0; i < maintainPlans.size(); i++)
        {
            MaintainPlan maintainPlan = maintainPlans.get(i);
            List<MaintainPlanItem> maintainPlanItems = maintainPlanItemService.findMaintainPlanItemsByMaintainPlanId(maintainPlan.getId());
            WriteSheet sheet = EasyExcel.writerSheet(i + 1, maintainPlan.getName()).head(MaintainPlanItem.class)
                    .build();
            excelWriter.write(maintainPlanItems, sheet);
        }
        excelWriter.finish();
    }

}
